<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输权限名称" clearable v-model="name" @clear="searchPermission">
            <el-button slot="append" icon="el-icon-search" @click="searchPermission"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加权限</el-button>
        </el-col>
      </el-row>
      <el-table :data="permissionList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="权限名称" prop="name"></el-table-column>
        <el-table-column label="权限路径" prop="url"></el-table-column>
        <el-table-column label="权限类型">
          <template slot-scope="sc">{{ sc.row.urlType == 1 ? "菜单权限" : "接口权限" }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 拿到整行数据  scope.row可以将整行所有的参数(整个对象的值)来进行传递-->
          <template slot-scope="scope">
            <el-button type="warning" size="mini" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="removePermissionById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!--添加权限-->
    <el-dialog title="添加权限" :visible.sync="addDialogVisible" width="50%" @close="addPermissionFormClose">
      <!-- :label-position 对齐-->
      <!-- ref 指定-->
      <!-- :model 绑定数据-->
      <!-- label-width 标签间距 -->
      <!-- :rules 绑定验证规则   1.设置完成后验证规则会去找命名方法中的所有既定规则-->
      <el-form
        :model="addPermissionForm"
        :rules="addPermissionFormRules"    
        ref="addPermissionFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="addPermissionForm.name"></el-input>
        </el-form-item>
        <el-form-item label="权限路径">
          <el-input v-model="addPermissionForm.url"></el-input>
        </el-form-item>
        <el-form-item label="上级菜单">
          <el-select v-model="addPermissionForm.parentId" placeholder="请选择上级菜单">
            <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in allRoleMenuList"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限类型" prop="urlType">
          <el-select v-model="addPermissionForm.urlType" placeholder="请权限类型">
            <el-option label="菜单权限" value="1"></el-option>
            <el-option label="接口权限" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addPermission">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!--修改权限-->

    <el-dialog title="修改权限" :visible.sync="editDialogVisible" width="50%" @close="editDepartFormClose">
      <!-- 修改模态框-->
      <el-form
        :model="editPermissionForm"
        :rules="editPermissionFormRules"
        ref="editPermissionFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="editPermissionForm.name"></el-input>
        </el-form-item>
        <el-form-item label="权限路径">
          <el-input v-model="editPermissionForm.url"></el-input>
        </el-form-item>
        <el-form-item label="上级菜单">
          <el-select v-model="editPermissionForm.parentId" placeholder="请选择上级菜单">
            <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in allRoleMenuList"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限类型" prop="urlType">
          <el-select v-model="editPermissionForm.urlType" placeholder="请选择权限类型">
            <el-option label="菜单权限" value="1"></el-option>
            <el-option label="接口权限" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editPermission">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      editDialogVisible: false /*模态框默认为false 关闭状态*/,
      pageNum: 1,
      pageSize: 5,
      permissionList: [],
      allRoleMenuList: [], //菜单权限下拉列表
      total: 0,
      name: "", //权限名称
      addDialogVisible: false,
      urlTypeDesc: "菜单权限",
      addPermissionForm: {
        name: "",
        code: "",
        url: "",
        parentId: "",
        urlType: null,
      },
      editPermissionForm: {
        id: -1,
        name: "",
        code: "",
        parentId: "",
        url: "",
        urlType: null,
      },
      editPermissionFormRules: {
        name: [
          { required: true, message: "请输入权限名称", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "权限名称在3-20個字符之間",
            trigger: "blur",
          },
        ],
        code: [
          //   { required: true, message: "请输入权限编码", trigger: "blur" },
          //   {
          //     min: 3,
          //     max: 20,
          //     message: "权限编码必须是3~20个字符之间",
          //     trigger: "blur"
          //   }
        ],
        url: [
          //   { required: true, message: "请输入权限路径", trigger: "blur" },
          //   {
          //     min: 3,
          //     max: 100,
          //     message: "权限路径必须是3~100个字符之间",
          //     trigger: "blur"
          //   }
        ],
        urlType: [{ required: true, message: "请选择权限类型", trigger: "blur" }],
        parentId: [],
      },
      addPermissionFormRules: {
        name: [
          { required: true, message: "请输入权限名称", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "权限名称在3-20個字符之間",
            trigger: "blur",
          },
        ],
        code: [
          //   { required: true, message: "请输入权限编码", trigger: "blur" },
          //   {
          //     min: 3,
          //     max: 20,
          //     message: "权限编码必须是3~20个字符之间",
          //     trigger: "blur"
          //   }
        ],
        url: [
          //   { required: true, message: "请输入权限路径", trigger: "blur" },
          //   {
          //     min: 3,
          //     max: 100,
          //     message: "权限路径必须是3~100个字符之间",
          //     trigger: "blur"
          //   }
        ],
        urlType: [{ required: true, message: "请选择权限类型", trigger: "blur" }],
        parentId: [],
      },
    }
  },
  methods: {
    // 删除权限信息
    async removePermissionById(id) {
      const res = await this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err)

      if ("confirm" === res) {
        let url = this.$baseURL.dev + "/UrlPermission/removePermission/"

        /*使用了路径传参的方式*/
        this.axios.post(url + id).then((res) => {
          this.editDialogVisible = false //隐藏模态框
          this.searchPermission() //分页
          if (res.data.code == 200) {
            this.$message.success("删除成功")
          } else {
            this.$message.error("服务端异常，请联系管理员")
          }
        })

        // this.$api.permission
        //   .removePermission(id)
        //   .then(res => {
        //     if (res.data.code == "0000") {
        //       this.$message.success("删除成功");
        //       this.searchPermission();
        //     }
        //   })
        //   .catch(err => {
        //     this.$message.error("服务端异常，请联系管理员");
        //   });
      } else {
        this.$message.info("取消删除")
      }
    },
    //添加子权限
    showAddDialog(row) {
      this.addDialogVisible = true
    },
    //修改权限信息
    showEditDialog(row) {
      /*点击修改事件之后将模态框状态调整为true */
      this.editDialogVisible = true
      this.editPermissionForm.id = row.id
      this.editPermissionForm.name = row.name
      this.editPermissionForm.url = row.url
      this.editPermissionForm.code = row.code
      this.editPermissionForm.urlType = row.urlType
      this.editPermissionForm.parentId = row.parentId
      console.log(this.editPermissionForm.parentId)
    },
    editDepartFormClose() {
      this.$refs.editPermissionFormRef.resetFields()
    },
    //修改执行方法
    editPermission() {
     this.$refs.editPermissionFormRef.validate((valid) => {
        if (!valid) return
  
        })

      let url = this.$baseURL.dev + "/UrlPermission/updatePer"
      this.axios.post(url, this.editPermissionForm).then((res) => {
        this.editDialogVisible = false
        this.searchPermission()
        if (res.data.code == 200) {
          this.$message.success("更新成功")
        } else {
          this.$message.error("服务端异常，请联系管理员")
        }
      })

      // this.$refs.editPermissionFormRef.validate(valid => {
      //   if (!valid) {
      //     this.$alert("valid fail");
      //     return;
      //   } else {
      //     this.$api.permission
      //       .updatePermission(this.editPermissionForm)
      //       .then(res => {
      //         this.editDialogVisible = false;
      //         this.$message.success("更新成功");
      //         this.searchPermission();
      //         this.getFirstLevelMenuList();
      //       })
      //       .catch(err => {
      //         this.$message.error("服务端异常，请联系管理员");
      //       });
      //   }
      // });
    },
    addPermission() {
      // 找当resfs中命名为addPermissionFormRef的组件
      //通过validate验证方法来进行判断    不符合验证时,状态为false 
      this.$refs.addPermissionFormRef.validate((valid) => {
        if (!valid) return
  
        })

        let url = this.$baseURL.dev + "/UrlPermission/addPer"
        this.axios.post(url, this.addPermissionForm).then((res) => {
          this.addDialogVisible = false
          this.searchPermission()
          if (res.data.code == 200) {
            this.$message.success("添加成功")
          } else {
            this.$message.error("服务端异常，请联系管理员")
          }
        })

      

      // this.$refs.addPermissionFormRef.validate(valid => {
      //   if (!valid) {
      //     this.$alert("valid fail");
      //     return;
      //   } else {
      //     this.$api.permission
      //       .createPermission(this.addPermissionForm)
      //       .then(res => {
      //         if (res.data.code !== "0000") {
      //           this.$message.error("添加失败");
      //         } else {
      //           this.addDialogVisible = false;
      //           this.$message.success("添加成功");
      //           this.searchPermission();
      //           this.getFirstLevelMenuList();
      //         }
      //       })
      //       .catch(err => {
      //         console.log(err);
      //         this.$message.error("服务端异常，请联系管理员");
      //       });
      //   }
      // });
    },
    addPermissionFormClose() {
      this.$refs.addPermissionFormRef.resetFields()
    },
    getPermissionList() {
      console.log("=====>" + this.name)
      let url = this.$baseURL.dev + "/UrlPermission/PageList"
      this.axios
        .get(url, {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            name: this.name,
          },
        })
        .then((res) => {
          console.log("=====>" + this.name)
          this.pageNum = res.data.pageNum
          this.pageSize = res.data.pageSize
          this.total = res.data.total
          this.permissionList = res.data.list
          console.log(this.permissionList)
        })

      /*
      this.$api.permission
        .getPermissionList({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name
        })
        .then(res => {
          console.log(res);

          if (res.data.code !== "0000") {
            this.$message.error("查询权限失败");
          } else {
            this.pageNum = res.data.result.current;
            this.pageSize = res.data.result.size;
            this.total = res.data.result.total;
            this.permissionList = res.data.result.records;
          }
        });
        */
    },
    searchPermission() {
      this.pageNum = 1
      this.pageSize = 10
      this.getPermissionList()
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.getPermissionList()
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage
      this.getPermissionList()
    },
    //新增菜单权限的时候，用于显示上级菜单列表，只查询一级菜单，因为系统只支持两级菜单
    getFirstLevelMenuList() {
      let url = "http://localhost:8083/UrlPermission/allRoleMenuList"
      console.log("🚀 -------", this.$baseURL.dev)

      this.axios.get(url, {}).then((res) => {
        if (res.data.data) {
          /*如果有参数就将allRoleMenuList 的值设置为-1 */
          this.allRoleMenuList = [{ id: -1, name: "无" }]
          /*循环所有查询到的列表,如果是-1那么一定是一级菜单*/
          let j = 1
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].parentId == -1) {
              /*然后利用$set函数，将循环出来的值set进allRoleMenuList 并且立即显示*/
              this.$set(this.allRoleMenuList, j, res.data.data[i])
              j++
            }
          }
        }
      })
      // this.$api.permission.getRoleMenuListWithListReturning().then(res => {
      //   console.log(res);
      //   if (res.data.code !== "0000") {
      //     this.$message.error("查询菜单权限失败");
      //   } else {
      //     if (res.data.result) {
      //       this.allRoleMenuList = [{id:-1,name:'无'}];
      //       let j = 1;
      //       for (let i = 0 ;i < res.data.result.length;i++) {
      //           if(res.data.result[i].parentId == -1){
      //               this.$set(this.allRoleMenuList, j, res.data.result[i]);
      //               j++;
      //           }
      //       }
      //     }
      //   }
      // });
    },
    reloadData() {
      //查询权限 列表
      this.searchPermission()
      //在添加权限时,下拉列表的数据
      this.getFirstLevelMenuList()
    },
  },
  created() {
    this.reloadData()
  },
}
</script>
<style lang="less" scoped></style>
